package com.yifang.yibingproject.utils;

import com.yifang.yibingproject.exception.ServiceException;
import io.jsonwebtoken.*;

import java.util.Date;
import java.util.Map;

/**
 * JWT工具类
 */
public class JwtUtils {
    private static final String KEY = "weixun-dailubao";

    /**
     * 生成TOKEN
     *
     * @param map
     * @return
     */
    public static String generateToken(Map<String, Object> map) {
        String userId = String.valueOf(map.get("userId"));
        if (userId == null) {
            throw new ServiceException("token参数缺少userId");
        }
        return Jwts.builder()
                .setHeaderParam(Header.TYPE, "JWT")
                .addClaims(map)
                .setId(userId)
                .setIssuer("宜宾")
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, KEY)
                .compact();
    }

    /**
     * 解析TOKEN
     *
     * @param token
     * @return
     */
    public static Claims parseToken(String token) {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(KEY).parseClaimsJws(token);
        return claimsJws.getBody();
    }

    public static String getUserIdFromToken(String token) {
        Claims claims = parseToken(token);
        return claims.getId();
    }

    public static String getRedisTokenKey(String userId) {
        return "user::token::" + userId;
    }

    public static String getRedisTokenKey(Long userId) {
        return "user::token::" + userId;
    }

    public static String getRedisAuthKey(String userId) {
        return "user::auth::" + userId;
    }

    public static String getRedisAuthKey(Long userId) {
        return "user::auth::" + userId;
    }

    public static String getRedisTokenKeyFromToken(String token) {
        return getRedisTokenKey(getUserIdFromToken(token));
    }

    public static String getRedisAuthKeyFromToken(String token) {
        return getRedisAuthKey(getUserIdFromToken(token));
    }

    public static void main(String[] args) {
        JwtBuilder jwtBuilder = Jwts.builder()
                .setId("10086")
                .setIssuer("中国移动")
                .setIssuedAt(new Date())
                .setSubject("中国移动")
                .signWith(SignatureAlgorithm.HS256, "china");
        String token = jwtBuilder.compact();
        System.out.println(token);
    }

}
